package za.co.dylanjaneke.airdownloader.command
{
	import com.adobe.serialization.json.JSON;
	
	import flash.display.NativeWindow;
	import flash.display.NativeWindowInitOptions;
	import flash.display.NativeWindowSystemChrome;
	import flash.display.NativeWindowType;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.geom.Rectangle;
	import flash.html.HTMLLoader;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.controls.HTML;
	import mx.core.FlexGlobals;
	import mx.managers.FocusManager;
	import mx.managers.IFocusManagerComponent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	import mx.utils.StringUtil;
	
	import za.co.dylanjaneke.airdownloader.events.LoadTrackedShowsEvent;
	import za.co.dylanjaneke.airdownloader.model.HomeScreenPM;
	import za.co.dylanjaneke.airdownloader.model.ScreenNavigatorPM;
	import za.co.dylanjaneke.airdownloader.model.SettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.StatusPM;
	import za.co.dylanjaneke.airdownloader.model.TrackerSettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.WeekViewPM;
	import za.co.dylanjaneke.airdownloader.model.vo.DayEntryVO;
	import za.co.dylanjaneke.airdownloader.model.vo.ShowVO;

	/**
	 * Author: Dylan Janeke.
	 */
	[Name("loadTrackedShowsCommand")]
	public class LoadTrackedShowsCommand
	{
		[Inject]
		public var screenNavigatorPM:ScreenNavigatorPM;
		
		[Inject]
		public var settingsPM:TrackerSettingsScreenPM;
				
		[Inject]
		public var weekViewPM:WeekViewPM;
		
		[Inject]
		public var homeScreenPM:HomeScreenPM;
		
		[Inject]
		public var statusPM:StatusPM;
		
		[Observer]
		public function handleLoadTrackedShowsEvent(event:LoadTrackedShowsEvent): void
		{
			statusPM.status= "loading tracked shows...";
			
			var loader:URLLoader= new URLLoader();
			
			loader.addEventListener(Event.COMPLETE, onLoadTrackedShowsComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onLoadTrackedShowsIoError);
			
			var request:URLRequest= new URLRequest("http://www.sidereel.com/users");
			try{
				loader.load(request);
			}
			catch(error:Error)
			{
				Alert.show("Tracked shows could not be loaded.","Error");
			}				
		}
		
		protected function onLoadTrackedShowsComplete(event:Event): void
		{
			
			statusPM.status= "building weekly calender...";
			
			var loader:URLLoader= URLLoader(event.target);
			
			XML.ignoreWhitespace= false;
			XML.prettyPrinting= false;
			XML.ignoreComments= true;
			default xml namespace= new Namespace("http://www.w3.org/1999/xhtml");
			
			var html:XML=null;
			var rez:String="";
			for each(var s:String in loader.data.split(/\n/))
			{
				if(StringUtil.trim(s).length<1 ||
					StringUtil.trim(s).indexOf("<![if gte IE 8]>")>-1 ||
						StringUtil.trim(s).indexOf("<![endif]>")>-1)
				{
					continue;
				}
					rez= rez+ s +"\n";
			}
			try
			{
				
				html= XML(rez);
				trace("h-->"+html.toXMLString());
			}
			catch(error:Error){
				Alert.show("Please report this issue on code.google.com/p/vicariousdownlader and reference this error [" + error.message +"]", "Unknown Error");
				return;
			}
			
			try
			{
				var calenderContainerz:XMLList =html..div.(hasOwnProperty("@id") && @id == "calendar-container");
				var calenderContainer:XML = calenderContainerz[0];
				var calenderDaysXML:XMLList=calenderContainer..li;
				
				var shows:ArrayCollection= new ArrayCollection();
				var i:int=0;
				for each (var calenderDay:XML in calenderDaysXML)
				{
					i++;
					if(i<4||i>(calenderDaysXML.length()-3))//sidereel changed to show more days- we still just want the current week.
						continue;
					
					var dayEntryVO:DayEntryVO= new DayEntryVO();
					dayEntryVO.date= StringUtil.trim(calenderDay.div.h2.span);
					dayEntryVO.current= 
						calenderDay.toXMLString().indexOf("class=\"current\"") > -1;
					
					statusPM.status = "building day " + dayEntryVO.date;
					
					var calenderEntriesXML:XMLList= calenderDay.div.div.div;
					
					for each( var calenderEntryXML:XML in calenderEntriesXML)
					{
						var episodeKey:String= calenderEntryXML.a.@href;
						var showName:String= calenderEntryXML.a;
						var episodeName:String = calenderEntryXML.div.a;
						
						var vo:ShowVO= new ShowVO(StringUtil.trim(showName), 
							StringUtil.trim(episodeName), StringUtil.trim(episodeKey));
						dayEntryVO.shows.addItem(vo);	
						trace(vo.episodeName);
					}
					shows.addItem(dayEntryVO);
				}
				weekViewPM.shows= shows;
				homeScreenPM.switchView(HomeScreenPM.WEEK);
				screenNavigatorPM.switchView(ScreenNavigatorPM.HOME);
				statusPM.status="http://code.google.com/p/vicariousdownloader/";
			}
			catch(error:Error)
			{
				trace(error.message);
				trace(error);
				Alert.show("It seems that sidereel has changed stuff in their website, please contact dylancjaneke@gmail.com for an updated version, or check http://code.google.com/p/vicariousdownloader/.","Unknown Error Occurred");		
			}
		}
		
		protected function onLoadTrackedShowsIoError(event:IOErrorEvent): void
		{
			Alert.show("I/O Error", "Error");	
		}
	}
}